<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input v-model="spuForm.spuName" placeholder="请输入SPU名称" clearable />
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select v-model="spuForm.tmId" placeholder="请选择SPU品牌" clearable style="width: 240px;">
          <el-option
            v-for="item in allTrademark"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spuForm.description"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="请输入描述"
        />
      </el-form-item>

      <el-form-item label="SPU图标">
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="hPictureCardPreview"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="SPU销售属性">
        <el-select v-model="saleAttrIDAndName" :placeholder="`还有${unSelectSaleAttr.length}个销售属性未选择`" clearable style="width: 240px; margin-right: 10px">
          <el-option
            v-for="item in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          />
        </el-select>
        <el-button type="primary" icon="plus" @click="hAddSale" :disabled="!saleAttrIDAndName">添加销售属性</el-button>
        <el-table :data="spuSaleAttr" border style="margin-top: 10px;">
          <el-table-column label="序号" width="80" type="index" />
          <el-table-column prop="saleAttrName" label="属性" width="180" />
          <el-table-column prop="spuSaleAttrValueList" label="属性值">
            <template #="{row, $index}">
              <el-tag
                v-for="tag in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice($index,1)"
                style="margin-right: 5px"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.flag"
                ref="InputRef"
                v-model="row.inputValue"
                style="width:150px"
                size="small"
                @blur="handleInputConfirm(row)"
              />
              <el-button v-else icon="plus" size="small" @click="showInput(row)"></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #="{row, $index}">
              <el-button size="small" type="danger" icon="delete" @click="spuSaleAttr.splice($index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      
      <el-form-item label="">
        <el-button type="primary" @click="hSaveSpu" :disabled="!(spuSaleAttr.length>0)">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { SaleAttrValue, SpuValue,AllTradeMark, SaleAttrResponse, SpuImages, SpuSaleAttrResponse, Records, TradeMark, SaleAttr, SpuImage, SpuSaleAttr } from '@/api/product/spu/type';
import { reqAllTrademarks, reqAllSales, reqSpuImage, reqSpuSaleAttr, reqAddSpu } from '@/api/product/spu';
import { ref, computed, nextTick, defineEmits } from 'vue';
import { UploadProps, ElMessage } from 'element-plus';

let dialogVisible = ref<boolean>(false) // spu图片预览
let dialogImageUrl = ref<string>('') //  spu图片预览
let saleAttrIDAndName = ref<any>('') // spu销售属性 增加属性值
let InputRef = ref() // 获取input实列
let spuForm = ref<SpuValue>({
  spuName: '',
  description: '',
  category3Id: '',
  tmId: '',
  spuSaleAttrList: [],
  spuImageList: [],
})
let allTrademark = ref<TradeMark[]>([]) // 所有的品牌
let allSaleAttr = ref<SaleAttr[]>([]) // 所有的销售属性
let spuImageList = ref<SpuImage[]>([]) // 当前的 spu图片
let spuSaleAttr = ref<SpuSaleAttr[]>([]) // 当前的 spu销售属性
let $emit = defineEmits()

const cancle = ()=>{
  $emit('changeIsTable', {val1:0, val2:''})
}
// 清空数据
const clearData = ()=>{
  Object.assign(spuForm.value, {
    spuName: '',
    description: '',
    category3Id: '',
    tmId: '',
    spuSaleAttrList: [],
    spuImageList: [],
  })
  spuImageList.value = []
  spuSaleAttr.value = []
  saleAttrIDAndName.value = ''
}
// 新增 
const initAddSpu = async (c3id:number)=>{
  // 添加c3Id
  spuForm.value.category3Id = c3id
  // 获取所有的品牌
  const res1:AllTradeMark = await reqAllTrademarks()
  allTrademark.value = res1.data
  // 获取所有的销售属性
  const res2:SaleAttrResponse = await reqAllSales()
  allSaleAttr.value = res2.data
}
// 编辑 - 获取所有的spu详细数据
const initSpuData = async (row:SpuValue)=>{
  spuForm.value = {...row}
  // 获取所有的品牌
  const res1:AllTradeMark = await reqAllTrademarks()
  allTrademark.value = res1.data
  // 获取所有的销售属性
  const res2:SaleAttrResponse = await reqAllSales()
  allSaleAttr.value = res2.data
  // 获取当前的 spu图片
  const res3:SpuImages = await reqSpuImage((row.id as number))
  spuImageList.value = res3.data.map(item => {
    return{
      name:item.imgName,
      url:item.imgUrl,
    }
  })
  // 获取当前的 spu销售属性
  const res4:SpuSaleAttrResponse = await reqSpuSaleAttr((row.id as number))
  spuSaleAttr.value = res4.data
}
// 添加销售属性
const hAddSale = ()=>{
  // 结构选择的 value
  let [baseSaleAttrId, saleAttrName] = saleAttrIDAndName.value.split(':')
  let newSaleAttr:SpuSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList:[]
  }
  spuSaleAttr.value.push(newSaleAttr) // 表格添加一条数据
  saleAttrIDAndName.value = '' // 清空选择
}
// spu 图片src
const hPictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// tag 编辑部分 显示 input
const showInput = (row:SpuSaleAttr) =>{
  row.flag = true
  row.inputValue = ''
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
// 添加 新的tag
const handleInputConfirm = (row:SpuSaleAttr) => {
  let {inputValue, baseSaleAttrId} = row
  // 1. 非法情况 为空return
  if((inputValue as string).trim()=='') return ElMessage({type: 'error',message: '属性值不能为空！'})
  // 2. 非法情况 重复return
  let a = row.spuSaleAttrValueList.find((item:any) => {
    return item.saleAttrValueName == inputValue
  })
  if(a) return ElMessage({type: 'error',message: '属性值不能重复！'})

  // 添加进 spu 销售属性中
  let newArr:SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: (inputValue as string),
  }
  row.spuSaleAttrValueList.push(newArr)
  row.flag = false
  row.inputValue = ''
}

// 确认保存 spu 数据
const hSaveSpu = async ()=>{
  // 整理数据
  spuForm.value.spuImageList = spuImageList.value.map((item:any) => {
    return{
      imgName:item.name,
      imgUrl:(item.response&&item.response.data)||item.url,
    }
  })
  spuForm.value.spuSaleAttrList = spuSaleAttr.value
  // 发请求
  let res:any = await reqAddSpu(spuForm.value)
  if(res.code!=200) return ElMessage({type: 'error',message: spuForm.value.id?'修改失败':'添加失败'})
  ElMessage({type: 'success',message: spuForm.value.id?'修改成功':'添加成功'})
  // 传值父组件
  $emit('changeIsTable', {val1:0, val2:spuForm.value.id?'edit':'add'})
}

// 计算 - 当前spu还未使用的属性
let unSelectSaleAttr = computed(()=>{
  let unSellectArr =  allSaleAttr.value.filter(item =>{
    return spuSaleAttr.value.every(item1 => {
      return item.name != item1.saleAttrName
    })
  })
  return unSellectArr
})
// 暴露方法
defineExpose({initSpuData, initAddSpu, clearData})
</script>

<style lang="scss" scoped>

</style>